package com.qq.connect.demo;

import DB.DB_connection_pool;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.PageFans;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.PageFansBean;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.javabeans.weibo.Company;
import com.qq.connect.oauth.Oauth;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Clock;
import java.util.ArrayList;

/**
 * Date: 12-12-4
 * Time: 下午4:36
 */
public class AfterLoginRedirectServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

            String accessToken = null;
            String openID = null;
            long tokenExpireIn = 0L;
            
            if (accessTokenObj.getAccessToken().equals("")) {
//                我们的网站被CSRF攻击了或者用户取消了授权
//                做一些数据统计工作
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();    //获取授权码
                tokenExpireIn = accessTokenObj.getExpireIn();     //accessToken缓存时间(默认三个月)

                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                
                request.getSession().setAttribute("demo_openid", openID);
                // 利用获取到的accessToken 去获取当前用户的openid --------- end

                ///******************************************************/////////
                String select_qq_id = "select * from land_table where QQ_open_id = '"+openID+"'";
                
                
				try {
					Connection db = DB_connection_pool.data_pool.getConnection();
					PreparedStatement ps_select= db.prepareStatement(select_qq_id);
	    			ResultSet rs =  ps_select.executeQuery();
	    			if(!rs.next()){     //第一次使用QQ登录
	    				    Clock clock = Clock.systemUTC();
	    	        		String user_account = String.valueOf((int)(Math.random()*90000)+10000)+clock.millis();      //产生用户账号
	    	                String insert_land_table_sql = "insert into land_table(user_account,QQ_open_id) values('"+user_account+"','"+openID+"')";    //登陆表
	    	                PreparedStatement ps = db.prepareStatement(insert_land_table_sql);
	    	                ps.executeUpdate();
	    	                
	    	                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
	    	                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
	    	                String nickname = userInfoBean.getNickname();     //获取qq用户昵称
	    	                String user_photo_path = userInfoBean.getAvatar().getAvatarURL100();    //获取qq用户头像url
	    	                
	    	                com.qq.connect.api.weibo.UserInfo weiboUserInfo = new com.qq.connect.api.weibo.UserInfo(accessToken, openID);
	    	                com.qq.connect.javabeans.weibo.UserInfoBean weiboUserInfoBean = weiboUserInfo.getUserInfo();
	    	                String autograph = weiboUserInfoBean.getIntroduction();   //用户腾讯微博简介
	    	                
	    	                String insert_user_data_sql = "insert into user_data(user_account,user_nickname,user_photo_path,user_introduction) values('"+user_account+"','"+nickname+"','"+user_photo_path+"','"+autograph+"')";   //用户信息表
	    	                
	    	                PreparedStatement ps_1 = db.prepareStatement(insert_user_data_sql);
	    	   		        ps_1.executeUpdate();
	    	   		        
	    	   		        ps.close();
	    	   		        ps_1.close();
	    	   		        
	    	   		     response.sendRedirect("index.jsp?user_account="+user_account);
	    	   		        
	    			}else{
	    				response.sendRedirect("index.jsp?user_account="+rs.getString("user_account"));
	    			}
	    			
	    			
	    			rs.close();
	    			ps_select.close();
	    			db.close();
	    			
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}   //获取连接
  
     
            }
        } catch (QQConnectException e) {
        }
    }
}
